//socket连接实例
export default {
	install(Vue, options) {
		// 在Vue的原型上添加实例方法，以全局调用
		Vue.prototype.$wedoWebSocketClient = {
			bean: undefined,
			url: undefined,
			token: undefined,
			listenerMap: {
				//回调列表，可以收到消息，如果抛异常则会被断开，第一个参数的接受的数据，第二个参数是socket实例，第三个参数是getMessage方法
			},
			connect(url, token) {
				//断开旧的连接
				this.disConnect()
				//连接并且注册
				var bean
				try {
					// bean = new WebSocket(url)
					bean = url
				} catch (e) {
					//创建失败了,返回并且打印失败信息
					// err('webSocket连接创建失败!')
					// err(e.stack)
					return
				}
				this.url = url
				this.token = token
				bean.addEventListener("open", events => {
					log("socket服务连接成功,开始登陆!url:" + this.url + "  token:" + this.token)
					bean.send(this.getMessage(this.Func_User.FUNC_CODE, this.Func_User.CMD_REGISTERED, this.token))
				})
				bean.addEventListener("close", events => {
					if (this.token != undefined && this.url != undefined) {
						// this.$store.cacheStore.state.socketState=false
						err("webSocket连接断开,5秒后尝试重连!")
						setTimeout(() => {
							if (this.token != undefined && this.url != undefined) {
								log("正在尝试重连！")
								this.connect(this.url, this.token)
							}else{
								err("不满足重连条件!")
							}
						}, 5000)
					} else {
						err("webSocket连接已经成功断开!")
					}
				})
				bean.addEventListener("message", events => {
					var data
					try {
						data = JSON.parse(events.data)
					} catch (e) {
						//消息解析异常
						err("异常消息类型" + events.data)
						return
					}
					var keys = Object.keys(this.listenerMap)
					for (var i = 0, len = keys.length; i < len; i++) {
						var key = keys[i]
						try {
							this.listenerMap[key](data, this.bean, this.getMessage)
						} catch (e) {
							err('监听器异常，将被移除：' + key)
							err(e)
							delete this.listenerMap[key]
						}
					}
				})
				bean.addEventListener("error", events => {
					err('连接异常:' + events.data)
				})
				this.bean = bean
			},
			disConnect() {
				this.url = undefined
				this.token = undefined
				if (this.bean != undefined) {
					//关闭连接
					this.bean.close()
					this.bean = undefined
				}
			},
			addListener(tag, listener) {
				this.listenerMap[tag] = listener
			},
			removeListener(tag) {
				delete this.listenerMap[tag]
			},
			getMessage(func, cmd, data, tag) {
				return JSON.stringify({
					func,
					cmd,
					state: 0,
					data,
					tag: tag == undefined ? Date.now() : tag
				})
			},
			//所有的状态码定义
			WedoWebSocketState: {
				STATE_OK: 0,
				STATE_FAILD: -1
			},
			Func_Server: {
				FUNC_CODE: 0,
				//心跳
				CMD_HEART: 0,
				//通讯异常，例如内容格式不正确一类的，和业务无关，只和解析有关
				CMD_ERR: 1,
				//连接超时，连接20秒以内未注册的连接将会被断开
				CMD_REGISTERED_TIMEOUT: 2,
				//超时未通讯会被断开，默认1分钟
				CMD_MSG_TIMEOUT: 3,
			},
			//用户相关
			Func_User: {
				//功能码
				FUNC_CODE: 1,
				//注册
				CMD_REGISTERED: 0,
				//异地登录
				CMD_LOGOUT: 1,
				//注册
				CMD_RELOGIN: 2,
			}
		}
	}
}
